let articleMoudle = require('../model/articleMoudle')
let mditor = require("mditor");

module.exports = {
    showArticleAddPage(req, res) {
        if (!req.session.isLogin) {
            return res.redirect('/login')
        }
        res.render('article/add', {
            isLogin: req.session.isLogin,
            user: req.session.user
        })
    },
    postArticle(req, res) {
        let article = req.body
        article.ctime = new Date();
        console.log(article)
        //    return
        articleMoudle.postNewArticle(article, (err, results) => {
            console.log(err);

            if (err || results.affectedRows != 1) return res.json({
                status: 0,
                msg: '添加失败'
            })
            res.json({
                status: 1,
                id: results.insertId,
                msg: '添加成功'
            })
        })
    },
    showDetailPage(req, res) {
        let id = req.query.id
        articleMoudle.getArticleById(id, (err, results) => {
            if (err) return res.redirect('/')
            if (results.length !== 1) {
                return res.redirect('/')
            }
            // 创建一个md格式解析html格式对象
            let parser=new mditor.Parser()
            results[0].content=parser.parse(results[0].content)
            res.render('./article/info',{
                article:results[0],
                isLogin:req.session.isLogin,
                user:req.session.user
            })
        })
    },
    editArticle(req,res){
       let article =req.body
       article.ctime = new Date();
    //    console.log(article)
    //    return
       articleMoudle.editArticle(article,(err,results)=>{
           if(err || results.affectedRows!=1)return res.json({status:0,msg:'编辑失败'})
           res.json({status:1,msg:'操作成功',id:results.id})
       })
    },
    showArticleEdit(req,res){
        let id = req.query.id
        articleMoudle.showArticleEdit(id,(err,results)=>{
            if(err) return res.json(err)
            if (!req.session.isLogin) {
                return res.redirect('/login')
            }
            res.render('article/edit', {
                article:results[0],
                isLogin: req.session.isLogin,
                user: req.session.user
            })
            // console.log(results[0]);
            // return;
        })
    }
}